package com.jwl.idc.utils;

import android.os.Handler;
import android.os.Message;
import android.widget.TextView;

import com.jwl.idc.R;

/**
 * Created by liangfan on 2016/1/7.
 * 倒计时类
 */
public class CountDownTime {
    private TextView timeTv;
    private Handler timeHandler;
    private int countTime = 0;

    public CountDownTime( TextView timeTv) {
        this.timeTv = timeTv;
    }

    void initHandler(){
        if(timeHandler == null){
            timeHandler = new Handler(){
                @Override
                public void handleMessage(Message msg) {
                    super.handleMessage(msg);
                    if (countTime <= 0) {
                        timeTv.setText(timeTv.getResources().getString(
                                R.string.reget_verficat_code));
                        timeTv.setEnabled(true);
                        this.removeMessages(1);
                    }
                    if (countTime > 0) {
                        timeTv.setText(countTime + " ) S ");
                        countTime--;
                        Message message = this.obtainMessage(1);
                        this.sendMessageDelayed(message, 1000);
                    }
                }
            };
        }
    }

    //开始倒计时
    public void start(int time){
        countTime = time;
        timeTv.setEnabled(false);
        initHandler();
        Message message = timeHandler.obtainMessage(1);
        timeHandler.sendMessageDelayed(message, 1000);
    }
    //关闭倒计时
    public void close(){
        if(timeHandler != null)
            timeHandler.removeMessages(1);
        timeHandler = null;
        timeTv = null;
    }
}
